﻿using daonaite.core.Attribute;
using daonaite.core.Catche;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.IdentityModel.Tokens;
using SqlSugar;
using System.Reflection;
using System.Text;


namespace daonaite.api.extends
{
    public static class AddCore
    {
        /// <summary>
        /// 添加类库
        /// </summary>
        /// <param name="service"></param>
        /// <param name="nspace"></param>
        /// <returns></returns>
        public static IServiceCollection addDaonaiteCore(this IServiceCollection service, string nspace)
        {
            Assembly assembly = Assembly.Load(nspace);
            Type[] types = assembly.GetTypes();

            foreach (Type type in types)
            {

                //1 如果是 定义 特性的命名空间, 不加载
                //2 没有AutoLoad 特性的不加载

                if (type.Namespace == "daonaite.core.Attribute")
                {
                    continue;
                }

                var attribute = type.GetCustomAttribute(typeof(AutoLoadAttribute));
                if (attribute == null)
                {
                    continue;
                }

                Console.WriteLine($"加载{type.FullName}");
                service.AddScoped(type);
            }
            return service;

        }

        /// <summary>
        /// 添加jwt认证
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddJwt(this IServiceCollection services, IConfiguration configuration)
        {
            configuration = configuration.GetSection("jwt");
            var symmetricKeyAsBase64 = configuration["SigningKey"];
            var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
            var signingKey = new SymmetricSecurityKey(keyByteArray);

            services.AddAuthentication("Bearer").AddJwtBearer(option =>
            {
                option.TokenValidationParameters = new TokenValidationParameters()
                {
                    //验证发行者
                    ValidateIssuer = true,
                    ValidIssuer = configuration["Issuer"],
                    //验证接收者
                    ValidateAudience = true,
                    ValidAudience = configuration["Audience"],
                    //验证签名
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = signingKey,
                    //验证过期时间
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero,
                    RequireExpirationTime = true
                };
            });
            return services;
        }

        /// <summary>
        /// 添加数据库
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection Addsqlsugar(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddHttpContextAccessor();
            services.AddSingleton<ISqlSugarClient>(s =>
            {
                SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
                {
                    DbType = DbType.MySql,
                    ConnectionString = configuration["mysql"],
                    IsAutoCloseConnection = true,
                }, db => {
                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        Console.WriteLine(sql);
                    };
                });
                return sqlSugar;
            });
            return services;
        }


        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddCache(this IServiceCollection services, IConfiguration configuration)
        {
            string cache = configuration["cache"];
            if (cache == null)
            {
                Console.WriteLine("无缓存配置");
                return services;
            }

            switch (cache)
            {
                case "0":
                    {
                        services.AddMemoryCache();
                        services.AddSingleton<ICacheHelp, LocalCache>();
                        break;
                    }
                case "1":
                    {
                        string redisconnectstring = configuration["redis"];
                        if (redisconnectstring == null)
                        {
                            Console.WriteLine("无redis连接字符串");
                        }
                        else
                        {
                            services.AddSingleton<ICacheHelp>(new RedisCache(redisconnectstring));
                        }

                        break;
                    }
            }

            return services;
        }

    }
}
